import random

def merge_sort(arr):
    """二分归并排序主函数"""
    if len(arr) <= 1:
        return arr
    
    # 分割阶段
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])  # 递归排序左半部分
    right = merge_sort(arr[mid:]) # 递归排序右半部分
    
    # 合并阶段
    return merge(left, right)

def merge(left, right):
    """合并两个已排序的数组"""
    merged = []
    i = j = 0
    
    # 双指针遍历合并
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1
    
    # 添加剩余元素
    merged += left[i:]
    merged += right[j:]
    return merged

